<template>
  <div>
    <el-upload
        v-if="!type"
        id="upload"
        ref="upload"
        class="upload-demo" 
        list-type="picture-card"
        name="file"
        accept="image/png,image/jpeg,image/jpg,image/gif" 
        :action="uploadUrl"
        :headers = "headers"
        :multiple="multiple" 
        :limit="limit" 
        :before-upload="beforeUpload" 
        :on-remove="onRemove" 
        :file-list="fileList"
        :on-error="uploadError"
        :on-success="uploadSuccess"
        :on-exceed="onExceed">
        <i class="el-icon-plus"></i>
        <div slot="tip" class="el-upload__tip">图片格式为jpg、jpeg、png、gif，大小不能超过2M </div>
    </el-upload>
    <el-upload
        v-if="type == 1"
        class="upload-demo" 
        list-type="picture-card"
        name="file"
        accept="image/png,image/jpeg,image/jpg,image/gif" 
        :action="uploadUrl"
        :headers = "headers"
        :multiple="multiple" 
        :limit="limit" 
        :before-upload="beforeUpload" 
        :on-remove="onRemove" 
        :file-list="fileListArr"
        :on-error="uploadError"
        :on-success="uploadSuccess"
        :on-exceed="onExceed">
        <i class="el-icon-plus"></i>
        <div slot="tip" class="el-upload__tip">图片格式为jpg、jpeg、png、gif，大小不能超过2M </div>
    </el-upload>
  </div>
</template>

<script>
    export default {
        data(){
            return {
                uploadUrl:'',
                headers: {
                authorization: ''
                }
            }
        },
        props:{
            fileList:{
                type:Array,
                default:()=>[]
            },
            fileListArr:{
                type:Array,
                default:()=>[]
            },
            multiple:{
                type:Boolean,
                default:true
            },
            limit:{
                type:Number,
                default:null
            },
            type:{
                type:Number,
                default:null
            }
        },
        created() {
            let baseURL = window.sessionStorage.getItem("baseURL") || 'http://47.108.138.33:8082/';
            this.uploadUrl = baseURL + 'qiniu/upload'
            //获取token
            let getCookie = [];
            let getToken,str = '';
            getCookie = document.cookie.split("; ")
            getCookie.forEach((v,i) =>{
              if(getCookie.indexOf('vue_admin_template_token') == -1){
                str = getCookie[i];
                getToken = str.indexOf('=');
                this.headers.authorization = str.substring(getToken+1,str.length);
              }
            })
        },
        methods:{
            // 图片上传成功的回调
            uploadSuccess(res, file, fileList){    
                if(res.code===0){
                    //区分一个父页面多次调用组件的情况
                    if(this.type){
                      this.$emit('getImgArr', fileList)
                    }else{
                      this.$emit('getImg', fileList)
                    }
                }else{
                    this.$message.error(res.msg);
                }
            },
            // 图片上传出错的回调
            uploadError(err,file){
                this.$message.error('上传失败！');
            },
            // 图片上传之前的回调
            beforeUpload(file){
                // const isLt2M = file.size / 1024 / 1024 < 2;
                // if (!isLt2M) {
                //     this.$message.error("上传图片大小不能超过 2MB!");
                // }
                // const isJPG = (file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/gif');
                // if (!isJPG) {
                //     this.$message.error("上传头像图片格式为 jpg,jpeg,png,gif");
                // }
                // return isJPG && isLt2M;
              let _this = this
                return new Promise((resolve, reject) => {
                  let isLt2M = file.size / 1024 / 1024 < 10 // 判定图片大小是否小于10MB
                  if(!isLt2M) {
                      reject()
                  }
                  let image = new Image(), resultBlob = '';
                  image.src = URL.createObjectURL(file);
                  image.onload = () => {
                      // 调用方法获取blob格式，方法写在下边
                      resultBlob = _this.compressUpload(image, file);
                      resolve(resultBlob)
                  }
                  image.onerror = () => {
                      reject()
                  }
                })

            },
            /* 图片压缩方法-canvas压缩 */
            compressUpload(image, file) {
                let canvas = document.createElement('canvas')
                let ctx = canvas.getContext('2d')
                let initSize = image.src.length
                let { width } = image, { height } = image
                canvas. width = width
                canvas.height = height
                ctx.fillRect(0, 0, canvas.width, canvas.height)
                ctx.drawImage(image, 0, 0, width, height)
                
                // 进行最小压缩0.1
                let compressData = canvas.toDataURL(file.type || 'image/jpeg', 0.1)
                
                // 压缩后调用方法进行base64转Blob，方法写在下边
                let blobImg = this.dataURItoBlob(compressData)
                return blobImg
            },
             
            /* base64转Blob对象 */
            dataURItoBlob(data) {
                let byteString;
                if(data.split(',')[0].indexOf('base64') >= 0) {
                    byteString = atob(data.split(',')[1])
                }else {
                    byteString = unescape(data.split(',')[1])
                }
                let mimeString = data
                    .split(',')[0]
                    .split(':')[1]
                    .split(';')[0];
                let ia = new Uint8Array(byteString.length)
                for( let i = 0; i < byteString.length; i += 1) {
                    ia[i] = byteString.charCodeAt(i)
                }
                return new Blob([ia], {type: mimeString})
            },
            // 移除文件
            onRemove(file, fileList) {
                if(this.type){
                  this.$emit('getImgArr', fileList)
                }else{
                  this.$emit('getImg', fileList)
                }
            },
            // 文件超出数量限制
            onExceed(file, fileList) {
                this.$message.error(`只能上传${this.limit}张图片！`);
            }
        }
    }
</script>